import { Request, Response } from 'express';
import { AuthRequest } from '@/types';
import ApiResponse from '@/utils/api/api-response.util';
import userOnlineService from '@/services/monitor/user-online.service';
import { getLogger } from '@/utils/logger';
import { UserOnline } from '@/models/monitor/user-online.model';

// 创建模块专用的日志记录器
const consoleLogger = getLogger("online-controller");
const logger = getLogger("online-controller", {
	console: false,
});

/**
 * 在线用户监控控制器
 */
class OnlineController {
  /**
   * 查询在线用户列表
   * @param req 请求对象
   * @param res 响应对象
   */
  async list(req: AuthRequest, res: Response) {
    try {
      const { ipaddr, userName } = req.query;
      
      // 请求日志
      consoleLogger.info("获取在线用户列表请求", {
        query: req.query,
        operator: req.user?.userName || 'unknown',
      });
      
      // 查询在线用户列表
      const onlineUsers: UserOnline[] = await userOnlineService.getOnlineUserList(
        ipaddr as string | undefined,
        userName as string | undefined
      );
      
      // 结果日志
      logger.info("获取在线用户列表成功", {
        response: {
          count: onlineUsers.length,
        },
        operator: req.user?.userName || 'unknown',
      });
      
      // 返回分页数据
      ApiResponse.successWithTable(res, onlineUsers, onlineUsers.length);
    } catch (error) {
      // 详细的错误日志
      consoleLogger.error(`查询在线用户列表失败: ${error instanceof Error ? error.message : String(error)}`, {
        requestData: {
          query: req.query,
        },
        operator: req.user?.userName || 'unknown',
        stack: error instanceof Error ? error.stack : undefined
      });
      if (!res.headersSent) {
        ApiResponse.error(res, '查询在线用户列表失败', 500);
      }
    }
  }
  
  /**
   * 强制退出用户
   * @param req 请求对象
   * @param res 响应对象
   */
  async forceLogout(req: AuthRequest, res: Response) {
    try {
      const { tokenId } = req.params;
      const operator = req.user?.userName || 'admin';
      
      // 请求日志
      consoleLogger.info("强制退出用户请求", {
        params: req.params,
        tokenId,
        operator,
      });
      
      if (!tokenId) {
        consoleLogger.warn('强制退出用户 - tokenId为空', { operator });
        ApiResponse.error(res, '会话ID不能为空', 400);
        return;
      }
      
      // 强制退出用户
      const success = await userOnlineService.forceLogout(tokenId);
      
      // 结果日志
      logger.info("强制退出用户结果", {
        response: {
          tokenId,
          success,
        },
        operator,
      });
      
      if (success) {
        ApiResponse.success(res, null, '强制退出成功');
      } else {
        ApiResponse.error(res, '强制退出失败，会话可能已不存在', 404);
      }
    } catch (error) {
      // 详细的错误日志
      consoleLogger.error(`强制退出用户失败: ${error instanceof Error ? error.message : String(error)}`, {
        requestData: {
          params: req.params,
        },
        operator: req.user?.userName || 'unknown',
        stack: error instanceof Error ? error.stack : undefined
      });
      if (!res.headersSent) {
        ApiResponse.error(res, '强制退出用户失败', 500);
      }
    }
  }
}

export default new OnlineController(); 